<?php

namespace app\api\services;

use app\api\cache\Marketing;
use app\api\consDir\CommunityConst;
use app\api\consDir\ErrorConst;
use app\common\libs\Singleton;
use app\common\models\Card\Card;
use app\common\models\Card\CardUser;
use app\common\models\Community\Community;
use app\common\models\Community\CommunityUser;
use app\common\models\Member\Finance;
use app\common\models\Member\Member;
use app\common\models\Order\Order;
use app\common\models\Order\OrderAddress;
use app\common\models\Order\OrderGoods;
use app\common\models\Order\OrderShop;
use app\common\models\Order\ServiceOrder;
use app\common\models\Service\Service;
use app\common\models\Service\ServiceAmountLog;
use app\common\models\Service\ServiceProfitPoolLog;
use app\common\models\Service\Services;
use app\common\models\Service\ServicesOrder;
use app\common\models\Service\ServicesOrderDetail;
use app\common\models\Service\ServiceTag;
use app\common\models\Shop\Shop;
use app\common\utils\CommonUtil;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

class ServiceCenterService
{
    use Singleton;

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function serviceList($page, $pageSize, $userId): array
    {
        $where = [
            ['deleted', '=', 0],
            ['user_id', '=', $userId]
        ];
        $list = Service::getInstance()
            ->where($where)
            ->page($page, $pageSize)
            ->order('id desc')
            ->select();
        if (empty($list)) {
            return [];
        }
        foreach($list as &$v){
            $v['allAddress'] = $v['service_province'].$v['service_city'].$v['service_country'].$v['detail_address'];
        }
        return $list->toArray();
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function serviceNearbyList($page, $pageSize, $lng, $lat): array
    {
        $where = [
            ['status', '=', 0],
            ['deleted', '=', 0],
        ];

        $juli = "ROUND(
        6378.138 * 2 * ASIN(
            SQRT(
                POW(
                    SIN(
                        (
                            " . $lat . " * PI() / 180 - lat * PI() / 180
                        ) / 2
                    ),
                    2
                ) + COS(" . $lat . " * PI() / 180) * COS(lat * PI() / 180) * POW(
                    SIN(
                        (
                            " . $lng . " * PI() / 180 - lng * PI() / 180
                        ) / 2
                    ),
                    2
                )
            )
        ) * 1000
    )";
        //$km = 1000000;
        //$where[] = [\think\facade\Db::raw($juli), '<=', (int)$km];

        $list = Service::getInstance()
            ->where($where)
            ->field('*,' . $juli . '  AS km')
            ->page($page, $pageSize)
            ->order('km asc')
            ->select();
        if (empty($list)) {
            return [];
        }
        foreach ($list as $k => &$val) {
            $val['km'] = $val['km'] / 1000;
            $val['allAddress'] = $val['serviceProvince'].$val['serviceCity'].$val['serviceCountry'].$val['detailAddress'];
            $val['tagList'] = ServiceTag::getInstance()->where('id','in',$val['tag'])->field('id,name')->select();
            /*if ($km > 0 && $km < $val['km']) {
                unset($list[$k]);
            }*/
        }
        return $list->toArray();
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function orderDetail($orderNo,$serviceId,$userId): array
    {
        $where = [
            ['order_no', '=', $orderNo],
            ['service_id', '=', $serviceId],
        ];
        $order = Order::getInstance()
            ->where($where)
            //->field('id,status,order_no,user_id,sell_price,order_type,pay_price,postage,sale,pay_at,create_at,expire_at,is_comment,completion_at,check_user_id,service_id,take_time,take_mobile,check_user_id')
            ->order('id desc')
            ->find();
        if (empty($order)) {
            return [];
        }
        $order = $order->toArray();
        $map = [
            ['user_id','=',$userId],
            ['id','=',$serviceId],
            ['deleted','=',0]
        ];
        $service = Service::getInstance()->where($map)->count();
        if(empty($service)){
            return [];
        }
        $where = [
            ['order_no', '=', $orderNo],
        ];
        $orderShop = OrderShop::getInstance()->where($where)->find();
        // 供应商订单 没有 orderShop 数据，没有 shop_id
        if (empty($orderShop['shopId'])) {
            $order['shopInfo'] = [];
        } else {
            $order['shopInfo'] = ShopService::getInstance()->getShopInfoById(
                $orderShop['shopId'],
                'id,shop_logo,shop_name,kf_phone');
        }
        $orderInfo = OrderGoods::getInstance()->where($where)->field('is_freight_insurance,is_seven,status,quantity,sell_price,goods_id,goods_title,sku_title,goods_img')->select();
        $order['goodsInfo'] = $orderInfo;
        //核销信息
        $checkInfo = Member::getInstance()->where('id',$order['checkUserId'])->field('id,user_name,phone')->find();
        $checkInfo = !empty($checkInfo) ? $checkInfo : [];
        $order['checkInfo'] = $checkInfo;

        //买家信息
        $buyInfo = Member::getInstance()->where('id',$order['userId'])->field('id,user_name,phone')->find();
        $buyInfo = !empty($buyInfo) ? $buyInfo : [];
        $order['buyInfo'] = $buyInfo;
        $addressInfo = OrderAddress::getInstance()->where('order_no',$order['orderNo'])->field('province,city,country,address,real_name,phone')->find();
        $addressInfo = !empty($addressInfo) ? $addressInfo : [];
        $order['addressInfo'] = $addressInfo;
        return $order;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function checkList($userId, $page, $pageSize,$serviceId): array
    {
        $where = [
            ['check_user_id', '=', $userId],
            ['service_id','=',$serviceId]
        ];
        $list = Order::getInstance()
            ->where($where)
            ->page($page, $pageSize)
            ->field('id,status,order_no,user_id,sell_price,order_type,pay_price,postage,sale,pay_at,create_at,expire_at,is_comment,completion_at,check_user_id')
            ->order('completion_at desc,id desc')
            ->select();
        if (empty($list)) {
            return [];
        }
        $list = $list->toArray();

        foreach ($list as &$val) {
            $where = [
                ['order_no', '=', $val['orderNo']],
            ];
            $orderShop = OrderShop::getInstance()->where($where)->find();
            // 供应商订单 没有 orderShop 数据，没有 shop_id
            if (empty($orderShop['shopId'])) {
                $val['shopInfo'] = [];
            } else {
                $val['shopInfo'] = ShopService::getInstance()->getShopInfoById(
                    $orderShop['shopId'],
                    'id,shop_logo,shop_name,kf_phone');
            }

            $orderInfo = OrderGoods::getInstance()->where($where)->field('is_freight_insurance,is_seven,status,quantity,sell_price,goods_id,goods_title,sku_title,goods_img')->select();
            $val['goodsInfo'] = $orderInfo;
            $val['checkInfo'] = Member::getInstance()->where('id', $val['checkUserId'])->field('phone,user_name')->find();
        }
        return $list;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function orderList($page, $pageSize, $serviceId, $orderNo, $orderType, $userId): array
    {
        $where = [
            ['o.deleted', '=', 0],
        ];

        if(empty($serviceId)){
            $whereShop = [
                ['status','=',1],
                ['user_id','=',$userId]
            ];
            $shop = Shop::getInstance()->where($whereShop)->find();
            if(empty($shop)){
                return [];
            }
            $where[] = ['s.shop_id','=',$shop['id']];
        }

        if($serviceId){
            $where[] = ['o.service_id', '=', $serviceId];
        }
        /*if($orderType == 1){
            $where[] = ['order_type','in',[1,3]];
        }elseif($orderType == 2){
            $where[] = ['order_type','in',[2,4]];
        }*/

        $list = Order::getInstance()
            ->alias('o')
            ->leftJoin('order_shop s','o.order_no=s.order_no')
            ->leftJoin('member m','o.user_id=m.id')
            ->where($where)
            ->where('o.pay_at', 'not null')
            ->where(function ($query) use ($orderNo) {
                if(!empty($orderNo)){
                    $query->whereOr('m.phone','like','%'.$orderNo.'%');
                    $query->whereOr('o.take_mobile','like','%'.$orderNo.'%');
                    $query->whereOr('o.order_no','like','%'.$orderNo.'%');
                }
            })
            ->page($page,$pageSize)
            ->field('o.id,o.status,o.order_no,o.user_id,o.sell_price,o.order_type,o.pay_price,o.postage,o.sale,o.pay_at,o.create_at,o.expire_at,o.is_comment,o.service_id,o.check_user_id')
            ->order('o.id desc')
            ->select();

        if (empty($list)) {
            return [];
        }
        $list = $list->toArray();
        //echo Order::getInstance()->getLastSql();die;
        foreach ($list as &$val) {
            $where = [
                ['order_no', '=', $val['orderNo']],
            ];
            $orderShop = OrderShop::getInstance()->where($where)->find();
            // 供应商订单 没有 orderShop 数据，没有 shop_id
            if (empty($orderShop['shopId'])) {
                $val['shopInfo'] = (object) [];
            } else {
                $val['shopInfo'] = ShopService::getInstance()->getShopInfoById(
                    $orderShop['shopId'],
                    'id,shop_logo,shop_name,kf_phone');
            }

            $orderInfo         = OrderGoods::getInstance()->where($where)->field('is_freight_insurance,is_seven,status,quantity,sell_price,goods_id,goods_title,sku_title,goods_img')->select();
            $val['createAt']   = date('Y-m-d H:i', strtotime($val['createAt']));
            $expireTime        = strtotime($val['expireAt']) - time();
            $val['expireTime'] = max($expireTime, 0);
            $val['goodsInfo']  = empty($orderInfo) ? [] : $orderInfo->toArray();
        }
        return $list;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function createOrder($userId, $servicesUser, $orderNo, $deduction)
    {
        //card_type 卡类型 0标准卡 1特殊卡
        $where = [
            ['user_id','=',$userId],
            ['card_type','=',0],
            ['expire_at','>',date('Y-m-d H:i:s')]
        ];
        $cardUser = CardUser::getInstance()->where($where)->order('card_time_type desc')->find();
        $payPrice = $servicesUser['sellPrice'];
        $discountRate = 0;
        $discountPrice = 0;
        if($cardUser){
            $rate = Card::getInstance()->where('id',$cardUser['cardId'])->value('rate') ?: 0;
            if($rate > 0){
                $discountPrice = bcmul($servicesUser['sellPrice'],$rate*0.01,2);
                $discountRate = $rate;
            }else{
                $config = Marketing::getKeyData('service', 'service_config');
                if(isset($config['discount_rate']) && $config['discount_rate'] > 0){
                    $discountPrice = bcmul($servicesUser['sellPrice'],$config['discount_rate']*0.01,2);
                    $discountRate = $config['discount_rate'];
                }
            }
        }
        $payPrice = bcsub($payPrice,$discountPrice,2);
        if($deduction > 0){
            $finance = MemberService::getInstance()->finance($userId);
            if($finance['deduction'] < $deduction){
                CommonUtil::throwException(ErrorConst::PARAM_ERROR, '平台抵扣券不足');
            }
            $config = Marketing::getKeyData('marketing', 'deduction');
            if(!isset($config['service_status']) || $config['service_status'] != 1){
                return '未开启平台抵扣券';
            }
            $deductionRate = ServiceCenterService::getInstance()->getServiceDeductionRate($servicesUser);
            if($deductionRate <= 0){
                return '平台抵扣券错误';
            }
            $deductionMoney = bcmul($payPrice,$deductionRate*0.01,2);
            if($deduction > $deductionMoney){
                return '平台抵扣券超出可抵扣金额';
            }
            $payPrice = bcsub($payPrice,$deduction,2);
        }

        ServicesOrder::getInstance()->startTrans();
        try {
            $data = [
                'user_id' => $userId,
                'order_no' => $orderNo,
                'pay_price' => $payPrice,
                'expire_at' => date('Y-m-d H:i:s', strtotime('+5 minutes')),
                'services_id' => $servicesUser['servicesId'],
                'service_id' => $servicesUser['serviceId'],
                'cover_img' => $servicesUser['coverImg'],
                'title' => $servicesUser['title'],
                'price' => $servicesUser['sellPrice'],
                'count' => $servicesUser['count'],
                'discount_rate' => $discountRate,
                'deduction' => $deduction,
                'discount_price' => $discountPrice,
            ];
            $order = ServicesOrder::getInstance()->insert($data);
            if (!$order) {
                return '创建订单失败';
            }
            $data = [
                'title' => $servicesUser['title'],
                'market_price' => $servicesUser['marketPrice'],
                'sell_price' => $servicesUser['sellPrice'],
                'cost_price' => $servicesUser['costPrice'],
                'cover_img' => $servicesUser['coverImg'],
                'cate_id' => $servicesUser['cateId'],
                'content' => $servicesUser['content'],
                'remark' => $servicesUser['remark'],
                'rate' => $servicesUser['rate'],
                'user_id' => $userId,
                'services_id' => $servicesUser['servicesId'],
                'service_id' => $servicesUser['serviceId'],
                'count' => $servicesUser['count'],
                'expire_at' => $servicesUser['expireAt'],
                'is_order' => $servicesUser['isOrder'],
                'order_phone' => $servicesUser['orderPhone'],
                'can_start_time' => $servicesUser['canStartTime'],
                'can_end_time' => $servicesUser['canEndTime'],
                'items' => $servicesUser['items'],
                'order_no' => $servicesUser['orderNo'],
                'price' => $servicesUser['sellPrice'],
                'pay_price' => $payPrice,
            ];
            ServicesOrderDetail::getInstance()->insert($data);
        } catch (\Exception $e) {
            ServicesOrder::getInstance()->rollback();
            return $e->getMessage().$e->getLine();
        }
        ServicesOrder::getInstance()->commit();
        return true;
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function payCallback($payInfo): bool
    {
        $where = [
            ['order_no', '=', $payInfo['orderNo']],
            ['status', '=', 0] //未支付
        ];
        $order = ServicesOrder::getInstance()->where($where)->find();
        if (empty($order)) {
            return false;
        }
        if ($payInfo['payPrice'] > 0 && $payInfo['payStatus'] == 3) {
            $msg = '服务订单抵扣' . $payInfo['payPrice'];
            MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'pay_services', $payInfo['payPrice'], 1, $msg, $payInfo['orderNo']);
        }

        if($order['deduction'] > 0){
            MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'buy', $order['deduction'], 8, '订单抵扣', $payInfo['orderNo'],1,0,0);
        }

        //type 0购买服务 1立即付款
        $status = $order['type'] == 1 ? 2 : 1;
        $data = [
            'status' => $status,
            'pay_at' => date('Y-m-d H:i:s')
        ];
        //立即买单
        if($status == 2){
            $this->dividend($order);
            $data['check_time'] = date('Y-m-d H:i:s');
        }
        $ret = ServicesOrder::getInstance()->where($where)->update($data);
        if (!$ret) {
            return false;
        }

        //赠送贡献值
        if ($payInfo['payPrice'] > 0) {
            $msg = '生活馆订单消费，赠送贡献值，订单号' . $payInfo['orderNo'];
            MemberService::getInstance()->addFinanceLog($payInfo['userId'], 'service', $payInfo['payPrice'], 7, $msg, $payInfo['orderNo']);
        }

        //加入分佣池
        MemberService::getInstance()->profitPoolLog($order['userId'], $order['payPrice'], $order['orderNo'], $order['payPrice'], 8);
        $config= Marketing::getKeyData('service', 'service_config');
        if(isset($config['fy_status']) && $config['fy_status'] == 1){
            if($config['profit_pool_rate'] > 0){
                //存入分红池比例
                $money = bcmul($payInfo['payPrice'],$config['profit_pool_rate']*0.01,4);
                $data = [
                    'user_id' => $payInfo['userId'],
                    'order_price' => $payInfo['payPrice'],
                    'rate' => $config['profit_pool_rate'],
                    'amount' => $money,
                    'order_no' => $payInfo['orderNo'],
                ];
                ServiceProfitPoolLog::getInstance()->insert($data);
            }
        }

        return true;
    }

    public function createPromptOrder($price,$serviceId,$userId,$orderNo,$deduction = 0): bool
    {
        $payPrice = bcsub($price,$deduction,2);
        $data = [
            'user_id' => $userId,
            'order_no' => $orderNo,
            'pay_price' => $payPrice,
            'price' => $price,
            'service_id' => $serviceId,
            'type' => 1,
            'expire_at' => date('Y-m-d H:i:s', strtotime('+5 minutes')),
            'deduction' => $deduction
        ];
        ServicesOrder::getInstance()->insert($data);
        return true;
    }

    /**
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function dividend($order): bool
    {
        if (empty($order)) {
            return false;
        }

        if($order['payPrice'] <= 0){
            return true;
        }
        $config= Marketing::getKeyData('service', 'service_config');
        if(empty($config)){
            return false;
        }

        //立即购买生活馆收入
        $service = Service::getInstance()->where('id',$order['serviceId'])->find();

        //0购买服务 1立即付款
        if($order['type'] == 1){
            if($service['rate'] > 0){
                $money = bcadd($order['payPrice'],$order['deduction'],2);
                //让利
                $fee = bcmul($money,$service['rate']*0.01,2);
                $money = bcsub($money,$fee,2);
                $serviceRate = bcsub(100,$config['performance_rate'],2);
                $money = bcmul($money,$serviceRate*0.01,2);
                //假设生活馆分70%，平台拿30%，生活馆70%中的20%为业绩（由平台控制分配），按次数核销的项目，生活馆收益 =70%中剩下的80%，除以 N次
                $this->changeService($service['id'], 'service_add', $money, '服务订单收入', $order['orderNo']);
            }
        }else{
            $rate = Services::getInstance()->where('id',$order['servicesId'])->value('rate') ?: 0;
            if($rate <= 0){
                $rate = $service['rate'];
            }

            $price = bcadd($order['pay_price'],$order['deduction'],2);
            $money = $order['count'] > 0 ? bcdiv($price,$order['count'],2) : $price;

            if($rate > 0){
                $fee = bcmul($money,$rate*0.01,2);
                $money = bcsub($money,$fee,2);
                $serviceRate = bcsub(100,$config['performance_rate'],2);
                $money = bcmul($money,$serviceRate*0.01,2);
                //假设生活馆分70%，平台拿30%，生活馆70%中的20%为业绩（由平台控制分配），按次数核销的项目，生活馆收益 =70%中剩下的80%，除以 N次
                $this->changeService($service['id'], 'service_add', $money, '服务订单收入', $order['orderNo']);
            }
            $order['pay_price'] = $order['count'] > 0 ? bcdiv($order['pay_price'],$order['count'],2) : $order['pay_price'];
        }


        if(isset($config['fy_status']) && $config['fy_status'] == 1){
            $price = $order['payPrice'];
            //1立即付款
            $remark = '消费金额的';
            if($order['type'] == 1){
                if(isset($config['user_dividend_type']) && $config['user_dividend_type'] == 1){
                    //按商家让利
                    $platformFee = Service::getInstance()->where('id',$order['serviceId'])->value('rate');
                    $price = bcmul($order['payPrice'],$platformFee*0.01,2);
                    $remark = '让利的';
                }
            }else{
                if(isset($config['user_dividend_type']) && $config['user_dividend_type'] == 1) {
                    //按商家让利
                    $platformFee = Services::getInstance()->where('id', $order['servicesId'])->value('rate');
                    $price = bcmul($order['payPrice'], $platformFee * 0.01, 2);
                    $remark = '让利的';
                }
            }


            if($price <= 0){
                return false;
            }
            $rate        = $config['user_invite_rate'];
            $inviteMoney = bcmul($price, $rate * 0.01, 4);
            $member      = Member::getInstance()->where('id', $order['userId'])->find();
            if ($inviteMoney > 0 && $member['inviteId']) {
                $msg = '推广会员消费，获得直推会员消费收益，'. $remark . $rate . '%';
                MemberService::getInstance()->addFinanceLog($member['inviteId'], 'direct_member_earnings', $inviteMoney, 5, $msg, $order['orderNo'], 1, 2);
            }

            //合伙人
            $commId = Community::getInstance()->where('comm_id', $member['commId'])->value('id');
            $where = [
                ['community_id', '=', $commId],
                ['community_status', '=', CommunityConst::PERMANENT_STATUS],
            ];
            $community = CommunityUser::getInstance()->where($where)->find();
            if ($config['user_community_partner_rate'] > 0 && !empty($community) && $community['userId']) {
                $rate = $config['user_community_partner_rate'];
                $bonus = bcmul($price, $rate * 0.01, 4);
                $msg = '推广会员消费，获得社区合伙人收益，'. $remark . $rate . '%';
                MemberService::getInstance()->addFinanceLog($community['userId'], 'partner_earnings', $bonus, 5, $msg, $order['orderNo'],1,2);
            }

            //服务商收益
            $partner = MemberService::getInstance()->getMyPartnerInfo($order['userId']);
            if ($partner) {
                if ($partner['partnerId']) {
                    $rate  = $config['user_service_rate'];
                    $msg   = '推广会员消费，获得服务商收益，收益比例' . $rate . '%，订单' . $order['orderNo'];
                    $bonus = bcmul($price, $rate*0.01, 4);
                    MemberService::getInstance()->addFinanceLog($partner['partnerId'], 'service_earnings', $bonus, 5, $msg, $order['orderNo'], 1, 2);
                }
            }

            //平级服务商
            $userPingMember = Member::getInstance()->where('id',$order['userId'])->find();
            $myPartner = MemberService::getInstance()->getMyPartner($userPingMember);
            if ($myPartner) {
                if ($myPartner['id']) {
                    $rate  = $config['user_ping_service_rate'];
                    $msg   = '推广会员消费，获得平级服务商收益，收益比例' . $rate . '%，订单' . $order['orderNo'];
                    $bonus = bcmul($price, $rate*0.01, 4);
                    MemberService::getInstance()->addFinanceLog($myPartner['id'], 'ping_service_earnings', $bonus, 5, $msg, $order['orderNo'], 1, 2);
                }
            }

            //区域（省/市/区县）会员消费收益
            $partnerInfo = MemberService::getInstance()->getAgencyArr($member['provinceId'], $member['cityId'], $member['countryId'], $member['streetId']);
            if ($partnerInfo['provinceUid'] > 0) {
                $rate = $config['user_province_rate'];
                $bonus = bcmul($price, $rate * 0.01, 4);
                if ($bonus > 0) {
                    $msg = "推广会员消费，获得区域（" . $partnerInfo['provinceName'] . "）会员消费收益，". $remark . $rate . '%';
                    MemberService::getInstance()->addFinanceLog($partnerInfo['provinceUid'], 'province_user_earnings', $bonus, 5, $msg, $order['orderNo'], 1, 2);
                }
            }

            if ($partnerInfo['cityUid'] > 0) {
                $rate = $config['user_city_rate'];
                $bonus = bcmul($price, $rate * 0.01, 4);
                if ($bonus > 0) {
                    $msg = "推广会员消费，获得区域（" . $partnerInfo['cityName'] . "）会员消费收益，". $remark . $rate . '%';
                    MemberService::getInstance()->addFinanceLog($partnerInfo['cityUid'], 'city_user_earnings', $bonus, 5, $msg, $order['orderNo'], 1, 2);
                }
            }

            if ($partnerInfo['countryUid'] > 0) {
                $rate = $config['user_area_rate'];
                $bonus = bcmul($price, $rate * 0.01, 4);
                if ($bonus > 0) {
                    $msg = "推广会员消费，获得区域（" . $partnerInfo['countryName'] . "）会员消费收益，" . $remark . $rate . '%';
                    MemberService::getInstance()->addFinanceLog($partnerInfo['countryUid'], 'area_user_earnings', $bonus, 5, $msg, $order['orderNo'], 1, 2);
                }
            }
        }
        return true;
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function changeService($serviceId, $type, $amount, $msg, $orderNo = ''): bool
    {
        if(empty($serviceId)){
            return false;
        }
        $service = Service::getInstance()->where('id',$serviceId)->find();
        if(empty($service)){
            return false;
        }
        $this->addService($service, $type, $amount, $msg, $orderNo);
        return true;
    }

    private function addService($finance, $type, $amount, $msg, $orderNo): bool
    {
        if($amount <= 0){
            return false;
        }
        //判断是否减金额,
        $arr = [
            'change', //提现到余额
        ];
        $thisAmount = $finance['serviceAmount'];
        $status     = in_array($type, $arr) ? 2 : 1; //2减少

        if ($status == 1) {
            $alterAmount = bcadd($thisAmount, $amount, 2);
        } else {
            $alterAmount = bcsub($thisAmount, $amount, 2);
        }

        $data = [
            'user_id'      => $finance['userId'],
            'status'       => $status,
            'remark'       => $msg . '，当前生活馆余额' . $alterAmount,
            'log_type'     => $type,
            'this_amount'  => $thisAmount,
            'alter_amount' => $alterAmount,
            'amount'       => $amount,
            'order_no'     => $orderNo,
            'service_id'   => $finance['id'],
        ];
        ServiceAmountLog::getInstance()->insert($data);
        if ($status == 1) {
            Service::getInstance()->where(['id' => $finance['id']])->inc('service_amount', $amount)->update();
            Service::getInstance()->where(['id' => $finance['id']])->inc('all_service_amount', $amount)->update();
        } else {
            Service::getInstance()->where(['id' => $finance['id']])->dec('service_amount', $amount)->update();
        }

        return true;
    }

    public function getDeductionRate($serviceId){
        $deductionRate = 0;
        $config = Marketing::getKeyData('marketing', 'deduction');
        if(isset($config['service_status']) && $config['service_status'] == 1){
            $rate = Service::getInstance()->where('id',$serviceId)->value('rate') ?: 0;
            if($rate <= $config['one']){
                $deductionRate = $config['one_rate'];
            }elseif($rate <= $config['two']){
                $deductionRate = $config['two_rate'];
            }elseif($rate <= $config['three']){
                $deductionRate = $config['three_rate'];
            }
            if($rate > $config['four']){
                $deductionRate = $config['four_rate'];
            }
        }
        return $deductionRate;
    }

    public function getServiceDeductionRate($servicesUser){
        $deductionRate = 0;
        $config = Marketing::getKeyData('marketing', 'deduction');
        if(isset($config['service_status']) && $config['service_status'] == 1){
            $rate = Services::getInstance()->where('id',$servicesUser['servicesId'])->value('rate') ?: 0;
            if($rate <= 0){
                $rate = Service::getInstance()->where('id',$servicesUser['serviceId'])->value('rate') ?: 0;
            }
            if($rate <= $config['one']){
                $deductionRate = $config['one_rate'];
            }elseif($rate <= $config['two']){
                $deductionRate = $config['two_rate'];
            }elseif($rate <= $config['three']){
                $deductionRate = $config['three_rate'];
            }
            if($rate > $config['four']){
                $deductionRate = $config['four_rate'];
            }
        }
        return $deductionRate;
    }

}